package webSocket.handler;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.AttributeKey;
import util.constant.Constant;
import util.netty.WebsocektResponse;
import util.spring.SpringUtils;
import webSocket.channel.QQ_ChannelGroup;

public class WebSocketRegHandler extends SimpleChannelInboundHandler<Object>{
	
	@Autowired
	private QQ_ChannelGroup group = SpringUtils.getBean(QQ_ChannelGroup.class);
	
	private WebSocketServerHandshaker shaker = null;
	
	private SimpleDateFormat format = new SimpleDateFormat("HH:mm");
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		if(msg instanceof FullHttpRequest) {
			FullHttpRequest request = (FullHttpRequest) msg;
			
			WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory("ws://127.0.0.1"+Constant.NETTY_CONFIG.PORT, null, false);
			shaker = factory.newHandshaker(request);
			if(shaker == null) {
				WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
			}
			else {
				//Websocket建立长连接
				String name = URLDecoder.decode(request.uri().replace("/name=", ""), "UTF-8");
				shaker.handshake(ctx.channel(), request);
				System.out.println("用户:"+name+" 已建立连接!");
				
				//广播到其他channel,通知有用户上线
				WebsocektResponse response = new WebsocektResponse(Constant.RESPONSE.ON_LINE, name);
				
				//channel加入到小组
				ctx.channel().attr(AttributeKey.valueOf("name")).set(name);
				ctx.channel().attr(AttributeKey.valueOf("onlineTime")).set(format.format(new Date()));
				group.getChannelGroup().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)).retain());
				group.addChannel(ctx.channel());
				
				
				/*//将当前小组里的所有channel.name响应回去
				for(ChannelId id : group.getChannelIds()) {
					Channel channel = group.getChannelGroup().find(id);
					
					String onlineName = channel.attr(AttributeKey.valueOf("name")).get().toString();
					String onlineTime = channel.attr(AttributeKey.valueOf("onlineTime")).get().toString();
					
					WebsocektResponse currUserResponse = new WebsocektResponse(Constant.RESPONSE.ON_LINE, onlineName);
					currUserResponse.setHour(onlineTime);
					ctx.write(new TextWebSocketFrame(JSON.toJSONString(currUserResponse)).retain());
				}
				ctx.flush();*/
				
				
				System.out.println("在线人数:"+group.getChannelGroup().size());
			}
			
		}
		else if(msg instanceof TextWebSocketFrame) {
			//发送文本信息
			TextWebSocketFrame text = (TextWebSocketFrame) msg;
			ctx.fireChannelRead(text.retain());
		}
		else if(msg instanceof CloseWebSocketFrame) {
			//发送关闭通道信息
			String name = ctx.channel().attr(AttributeKey.valueOf("name")).get().toString();
			System.out.println("用户:"+name+" 已断开连接!");
			
			group.removeChannel(ctx.channel());
			WebsocektResponse response = new WebsocektResponse(Constant.RESPONSE.OUT_LINE, name);
			group.getChannelGroup().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(response)).retain());
			ctx.channel().close();
		}
		
	}

}
